package org.eremite.corm.party.address;

import org.eremite.corm.BaseArchetype;
import org.eremite.corm.party.Binding;
import org.eremite.corm.party.Party;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.FetchType;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Entity
public class AssociatedAddress extends BaseArchetype {

    @ManyToOne(cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE})
    private Party party;

    @ManyToOne(cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE})
    private Address address;

    @OneToMany(cascade={
            CascadeType.PERSIST,
            CascadeType.MERGE,
            CascadeType.REMOVE},
            fetch=FetchType.EAGER)
    private Set<Binding> properties = new HashSet<Binding>();

    public AssociatedAddress() {}

    public AssociatedAddress(
            Party party,
            Address address) {
        setParty(party);
        setAddress(address);
        party.addAddress(this);
        address.addParty(this);
    }

    public AssociatedAddress(
            Party party,
            Address address,
            String name,
            String description) {
        setParty(party);
        setAddress(address);
        setName(name);
        setDescription(description);
        party.getAddresses().add(this);
        address.getParties().add(this);
    }

    public Party getParty() {
        return party;
    }

    public void setParty(Party party) {
        this.party = party;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Set<Binding> getProperties() {
        return properties;
    }

    public void setProperties(Set<Binding> properties) {
        this.properties = properties;
    }

    public void addProperty(Binding ... properties) {
        getProperties().addAll(Arrays.asList(properties));
    }

    public void addProperty(Binding property){
        getProperties().add(property);
    }
}
